<?php

declare(strict_types=1);

namespace App\CustHub\Listener;

use App\CustHub\Dto\RobotLoginAfterDto;
use App\CustHub\Event\RobotLoginAfter;
use App\CustHub\Mapper\ChCorpMapper;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Mapper\ChRoomMapper;
use App\CustHub\Model\ChRobot;
use App\CustHub\Service\ChContactService;
use App\CustHub\Service\ChCorpService;
use App\CustHub\Service\ChRobotLoginLogService;
use App\CustHub\Service\ChRoomService;
use App\CustHub\Service\ChRoomSyncService;
use App\Robot\Service\RobotApiService;
use Carbon\Carbon;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Psr\Container\ContainerInterface;
use function Yansongda\Supports\value;

/**
 * 机器人登录事件监听
 */
#[Listener]
class RobotLoginListener implements ListenerInterface
{

    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function listen(): array
    {
        return [
            RobotLoginAfter::class,
        ];
    }

    public function process(object $event): void
    {
        /** @var RobotLoginAfterDto $data */
        $data = $event->data;

        $service = $this->container->get(ChRobotLoginLogService::class);
        $logData = [
            'robot_id' => $data->getRobotId(),
            'remark' => $data->getRemark(),
            'type' => $data->getType(),
//            'ip' => get_client_ip(),
            'created_at' => Carbon::now()->toDateTimeString()
        ];
        $service->save($logData);

        $robotInfo = $this->container->get(ChRobotMapper::class)->findById($data->getRobotId());

        // 同步企业信息
        if(empty($robotInfo->corp_id) && $robotInfo->login_status == 1){
            Coroutine::sleep(1);
            $corpInfo = $this->container->get(ChCorpService::class)->syncCorpDataByCorpId($robotInfo->id,$robotInfo->corp_wxid,$robotInfo->main_uid);
            if(!empty($corpInfo)){

                if($corpInfo->type == 1){
                    $this->container->get(ChCorpMapper::class)->model::query()
                        ->where('id',$corpInfo->id)
                        ->update([
                            'type' => 0
                        ]);
                }

                $robotInfo->corp_id = $corpInfo->id;
                $robotInfo->corp_name = $corpInfo->corp_name;
                $robotInfo->save();
                $this->container->get(ChRobotMapper::class)->clearCache($robotInfo->id);
            }
        }
    }
}